<?php

namespace Sharks\Core\Http\View;

use Sharks\Core\LifeCycle\Event;
use Sharks\Core\Module;
use Sharks\Core\Cfg\AppConfig;
use Sharks\Core\Http\Response;
use Sharks\Core\Support\Smarty\SmartyVariableProvider;
use Smarty;

/**
 * Smarty 视图表示
 */
abstract class AbstractSmartyView extends View {
    /** 默认的视图后辍名 */
    const DEFAULT_VIEW_SUFFIX = 'vue.php';

    protected $smarty;
    protected $data;

    public function __construct($data = null) {
        $this->data = is_null($data) ? array() : $data;
        $this->smarty = new smarty();
    }


    public function smarty() {
        return $this->smarty;
    }

    public function assign($name, $value) {
        $this->data[$name] = $value;
        return $this;
    }

    public function assigns($data) {
        array_merge($this->data, $data);
        return $this;
    }

    /**
     * 渲染Smarty引擎
     * @param Response $response
     */
    public function render(Response $response) {
        $this->beforeRender();

        $app = $response->app();

        //设置编译目录
        $this->smarty->setCompileDir($app->path()->app->storage . '/smarty/view');
        //缓存目录
        $this->smarty->setCacheDir($app->path()->app->storage . '/smarty/view_cache');
        $this->smarty->cache_lifetime = 0; //缓存时间
        $this->smarty->caching = true; //缓存方式

        // 处理插件
        $this->smarty->addPluginsDir($app->path()->framework->root . '/Support/Smarty');
        foreach (Module::all() as $name => $module) {
            $this->smarty->addPluginsDir($module->path()->root . '/Render/Smarty');
        }

        // 设置数据
        if (!empty($this->data)) {
            $this->smarty->assign($this->data);
        }

        $this->smarty->force_compile = true;

        Event::fire('viewing.smarty', $this);
        $provider = new SmartyVariableProvider();
        $provider->handle($this->smarty);
        // 再加上绝对路径
        $this->smarty->display($this->getViewPath()); //编译模板
        Event::fire('viewed.smarty', $this);
    }

    /**
     * 获得完整的view文件路径
     */
    public abstract function getViewPath();

    /**
     * 渲染前
     */
    public abstract function beforeRender();
}